package com.baidu.BaiduMap;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import java.net.URLDecoder;
import java.util.Map;

import me.gfuil.bmap.uri.sdk.BmapHelper;
import me.gfuil.bmap.uri.sdk.CoordinateUtils;
import me.gfuil.bmap.uri.sdk.Poi;
import me.gfuil.bmap.uri.sdk.StringUtils;

public class WelcomeScreen extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView text = findViewById(R.id.text);

    if (null != getIntent().getDataString()) {
      text.setText(getIntent().getDataString());

      navi();
    }

    text.setOnClickListener(v -> copy());
    findViewById(R.id.btn_feedback).setOnClickListener(v -> feedback());
    findViewById(R.id.btn_navi).setOnClickListener(v -> navi());
  }

  @Override
  protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    if (null != intent) {
      TextView text = findViewById(R.id.text);
      text.setText(intent.getDataString());
      setIntent(intent);

      navi();
    }
  }

  public void navi() {
    try {
      String dataUri = URLDecoder.decode(getIntent().getDataString());
      if (StringUtils.isEmpty(dataUri)) {
        Toast.makeText(this, "未找到位置信息", Toast.LENGTH_SHORT).show();
        return;
      }

      Log.i("bmap_", "navi: " + dataUri);

      Map<String, String> map = StringUtils.getUrlRequest(dataUri);

      if (null == map || map.isEmpty()) {
        Toast.makeText(this, "未找到位置信息", Toast.LENGTH_SHORT).show();
        return;
      }

      if (dataUri.startsWith("baidumap://map") || dataUri.startsWith("bdapp://map")) {
        String coord_type = "bd09";
        String latlng = null, address = null;

        coord_type = map.get("coord_type");

        if (dataUri.contains("map/show")) {
          latlng = map.get("center");
          address = "我的位置";
        } else if (dataUri.contains("map/marker")) {
          latlng = map.get("location");
          address = map.get("title");
        } else if (dataUri.contains("map/geocoder")) {
          latlng = map.get("location");
          address = map.get("address");
        } else if (dataUri.contains("map/navi")){
          String[] to = StringUtils.convertStrToArray(map.get("location"), "[,]");
          if (null != to) {
            Poi poi = new Poi();

            if (StringUtils.isEmpty(coord_type) || coord_type.startsWith("bd09")) {
              double[] lnglat = CoordinateUtils.bd09ToGcj02(StringUtils.getStringNumberDouble(to[1]),
                      StringUtils.getStringNumberDouble(to[0]));

              poi.setName(address);
              poi.setLatitude(lnglat[1]);
              poi.setLongitude(lnglat[0]);

            } else if ("gcj02".equals(coord_type)) {

              poi.setName(address);
              poi.setLatitude(StringUtils.getStringNumberDouble(to[0]));
              poi.setLongitude(StringUtils.getStringNumberDouble(to[1]));
            } else if ("wgs84".equals(coord_type)) {
              double[] lnglat = CoordinateUtils.wgs84ToGcj02(Double.parseDouble(to[1]),
                      Double.parseDouble(to[0]));

              poi.setName(address);
              poi.setLatitude(lnglat[1]);
              poi.setLongitude(lnglat[0]);
            }

            if (to.length == 3 && null != to[2]){
              poi.setName(to[2]);
            } else {
              poi.setName("出发点");
            }
            BmapHelper.route(this, BmapHelper.TYPE_MAP_DEFAULT, BmapHelper.TYPE_ROUTE_DRIVE, null, poi);
          }

          return;

        } else if (dataUri.contains("map/bikenavi") || dataUri.contains("map/walknavi")) {
          String[] from = StringUtils.convertStrToArray(map.get("origin"), "[,]");
          String[] to = StringUtils.convertStrToArray(map.get("destination"), "[,]");

          Poi start = null, end = null;
          if (null != from && from.length >= 2) {
            start = new Poi();
            start.setLatitude(StringUtils.getStringNumberDouble(from[0]));
            start.setLongitude(StringUtils.getStringNumberDouble(from[1]));

            if (from.length == 3 && null != from[2]){
              start.setName(from[2]);
            } else {
              start.setName("出发点");
            }

          }
          if (null != to) {
            end = new Poi();
            end.setLatitude(StringUtils.getStringNumberDouble(to[0]));
            end.setLongitude(StringUtils.getStringNumberDouble(to[1]));

            if (to.length == 3 && null != to[2]){
              end.setName(to[2]);
            } else {
              end.setName("目的点");
            }
          }

          if (StringUtils.isEmpty(coord_type) || coord_type.startsWith("bd09")) {
            if (null != start){
              double[] lnglat = CoordinateUtils.bd09ToGcj02(start.getLongitude(), start.getLatitude());

              start.setLongitude(lnglat[0]);
              start.setLatitude(lnglat[1]);
            }

            if (null != end){
              double[] lnglat = CoordinateUtils.bd09ToGcj02(end.getLongitude(), end.getLatitude());

              end.setLongitude(lnglat[0]);
              end.setLatitude(lnglat[1]);
            }

          } if ("wgs84".equals(coord_type)) {
            if (null != start){
              double[] lnglat = CoordinateUtils.wgs84ToGcj02(start.getLongitude(), start.getLatitude());

              start.setLongitude(lnglat[0]);
              start.setLatitude(lnglat[1]);
            }

            if (null != end){
              double[] lnglat = CoordinateUtils.wgs84ToGcj02(end.getLongitude(), end.getLatitude());

              end.setLongitude(lnglat[0]);
              end.setLatitude(lnglat[1]);
            }
          }


          int typeRoute = BmapHelper.TYPE_ROUTE_DEFAULT;
          if (dataUri.contains("bikenavi")){
            typeRoute = BmapHelper.TYPE_ROUTE_BIKE;
          } else if (dataUri.contains("walknavi")){
            typeRoute = BmapHelper.TYPE_ROUTE_WALK;
          }
          BmapHelper.route(this, BmapHelper.TYPE_MAP_DEFAULT, typeRoute, start, end);

          return;
        } else if (dataUri.contains("map/direction")) {
          Poi start = null, end = null;

          String[] origin = StringUtils.convertStrToArray(map.get("origin"), "[|]");
          if (null != origin){
            start = new Poi();
            for (String p : origin) {
              if (p.startsWith("name:")) {
                address = p.substring(5);
                start.setName(address);
              } else if (p.startsWith("latlng:")) {
                latlng = p.substring(7);

                if (StringUtils.isEmpty(coord_type) || coord_type.startsWith("bd09")) {
                  String[] latlngStrs = StringUtils.convertStrToArray(latlng, "[,]");
                  double[] lnglat = CoordinateUtils.bd09ToGcj02(StringUtils.getStringNumberDouble(latlngStrs[1]),
                          StringUtils.getStringNumberDouble(latlngStrs[0]));

                  start.setLatitude(lnglat[1]);
                  start.setLongitude(lnglat[0]);

                } else if ("gcj02".equals(coord_type)) {
                  String[] latlngStrs = StringUtils.convertStrToArray(latlng, "[,]");

                  start.setLatitude(StringUtils.getStringNumberDouble(latlngStrs[0]));
                  start.setLongitude(StringUtils.getStringNumberDouble(latlngStrs[1]));
                } else if ("wgs84".equals(coord_type)) {
                  String[] latlngStrs = StringUtils.convertStrToArray(latlng, "[,]");
                  double[] lnglat = CoordinateUtils.wgs84ToGcj02(Double.parseDouble(latlngStrs[1]),
                          Double.parseDouble(latlngStrs[0]));

                  start.setLatitude(lnglat[1]);
                  start.setLongitude(lnglat[0]);
                }

              }
            }
          }


          String[] destination = StringUtils.convertStrToArray(map.get("destination"), "[|]");
          if (null != destination){
            end = new Poi();
            for (String p : destination) {
              if (p.startsWith("name:")) {
                address = p.substring(5);
                end.setName(address);
              } else if (p.startsWith("latlng:")) {
                latlng = p.substring(7);

                if (StringUtils.isEmpty(coord_type) || coord_type.startsWith("bd09")) {
                  String[] latlngStrs = StringUtils.convertStrToArray(latlng, "[,]");
                  double[] lnglat = CoordinateUtils.bd09ToGcj02(StringUtils.getStringNumberDouble(latlngStrs[1]),
                          StringUtils.getStringNumberDouble(latlngStrs[0]));

                  end.setLatitude(lnglat[1]);
                  end.setLongitude(lnglat[0]);

                } else if ("gcj02".equals(coord_type)) {
                  String[] latlngStrs = StringUtils.convertStrToArray(latlng, "[,]");

                  end.setLatitude(StringUtils.getStringNumberDouble(latlngStrs[0]));
                  end.setLongitude(StringUtils.getStringNumberDouble(latlngStrs[1]));
                } else if ("wgs84".equals(coord_type)) {
                  String[] latlngStrs = StringUtils.convertStrToArray(latlng, "[,]");
                  double[] lnglat = CoordinateUtils.wgs84ToGcj02(Double.parseDouble(latlngStrs[1]),
                          Double.parseDouble(latlngStrs[0]));

                  end.setLatitude(lnglat[1]);
                  end.setLongitude(lnglat[0]);
                }
              }
            }

          }


          int typeRoute = BmapHelper.TYPE_ROUTE_DEFAULT;
          if ("driving".equals(map.get("mode"))){
            typeRoute = BmapHelper.TYPE_ROUTE_DRIVE;
          } else if ("transit".equals(map.get("mode"))){
            typeRoute = BmapHelper.TYPE_ROUTE_BUS;
          } else if ("walking".equals(map.get("mode"))){
            typeRoute = BmapHelper.TYPE_ROUTE_WALK;
          } else if ("riding".equals(map.get("mode"))){
            typeRoute = BmapHelper.TYPE_ROUTE_BIKE;
          }
          BmapHelper.route(this, BmapHelper.TYPE_MAP_DEFAULT, typeRoute, start, end);
          return;
        } else if (dataUri.contains("map/place/detail")) {
          if (BmapHelper.getBmapVersionCode(this) < 159){
            Toast.makeText(this, "暂不支持", Toast.LENGTH_SHORT).show();
            return;
          }
          BmapHelper.openPoiID(this, BmapHelper.TYPE_MAP_BAIDU, map.get("uid"));
        }

        if (StringUtils.isEmpty(latlng) || !latlng.contains(",")) {
          latlng = "0,0";

          String geo = "geo:" + latlng + "?q=" + address;

          Uri uri = Uri.parse(geo);
          Intent intent = new Intent(Intent.ACTION_VIEW, uri);
          intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          startActivity(intent);
          return;
        }

        if (StringUtils.isEmpty(address)) {
          address = "外部传来的位置";
        }


        Poi poi = new Poi();
        if (StringUtils.isEmpty(coord_type) || coord_type.startsWith("bd09")) {
          String[] latlngStrs = StringUtils.convertStrToArray(latlng, "[,]");
          double[] lnglat = CoordinateUtils.bd09ToGcj02(StringUtils.getStringNumberDouble(latlngStrs[1]),
                  StringUtils.getStringNumberDouble(latlngStrs[0]));

          poi.setName(address);
          poi.setLatitude(lnglat[1]);
          poi.setLongitude(lnglat[0]);

        } else if ("gcj02".equals(coord_type)) {
          String[] latlngStrs = StringUtils.convertStrToArray(latlng, "[,]");

          poi.setName(address);
          poi.setLatitude(StringUtils.getStringNumberDouble(latlngStrs[0]));
          poi.setLongitude(StringUtils.getStringNumberDouble(latlngStrs[1]));
        } else if ("wgs84".equals(coord_type)) {
          String[] latlngStrs = StringUtils.convertStrToArray(latlng, "[,]");
          double[] lnglat = CoordinateUtils.wgs84ToGcj02(Double.parseDouble(latlngStrs[1]),
              Double.parseDouble(latlngStrs[0]));

          poi.setName(address);
          poi.setLatitude(lnglat[1]);
          poi.setLongitude(lnglat[0]);
        }
        BmapHelper.marker(this, poi);
      } else {
        Toast.makeText(this, "暂不支持的链接", Toast.LENGTH_SHORT).show();
      }

      new Handler(Looper.getMainLooper()).postDelayed(this::finish, 1000);
    } catch (Exception e) {
      e.printStackTrace();
      Toast.makeText(this, "错误：" + e.getMessage(), Toast.LENGTH_SHORT).show();
    }
  }

  public void copy() {
    if (!StringUtils.isEmpty(getIntent().getDataString())) {
      ClipboardManager myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
      myClipboard.setPrimaryClip(ClipData.newPlainText("text", getIntent().getDataString()));
      Toast.makeText(WelcomeScreen.this, "链接已复制", Toast.LENGTH_SHORT).show();
    } else {
      Toast.makeText(WelcomeScreen.this, "无链接可复制", Toast.LENGTH_SHORT).show();
    }
  }

  public void feedback() {
    try {
      copy();
      Uri uri = Uri.parse(getString(R.string.link_feedback));
      Intent intent = new Intent(Intent.ACTION_VIEW, uri);
      startActivity(intent);
    } catch (Exception e) {
      e.printStackTrace();
      Toast.makeText(this, "错误：" + e.getMessage(), Toast.LENGTH_SHORT).show();
    }
  }
}
